﻿using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Expression.Interactivity;

namespace Com.CodePlex.SPC3.SPbAM.View {

	//http://stackoverflow.com/questions/1000040/selecteditem-in-a-wpf-treeview

	//requires Expression Blend 4
	/*
	<TreeView>		
		<ei:Interaction.Behaviors>		
		<behaviours:BindableSelectedItemBehaviour SelectedItem="{Binding SelectedItem}" />	
		</ei:Interaction.Behaviors>
	</TreeView>
	 * */

	public class BindableSelectedItemBehaviour : Behavior<TreeView> {

		public object SelectedItem {
			get { return (object)GetValue(SelectedItemProperty); }
			set { SetValue(SelectedItemProperty, value); }
		}    
		
		public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehaviour), new UIPropertyMetadata(null, OnSelectedItemChanged));
		
		private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) {
			var item = e.NewValue as TreeViewItem;
			if (item != null) {
				item.SetValue(TreeViewItem.IsSelectedProperty, true);
			}
		}

		protected override void OnAttached() {
			base.OnAttached();
			this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
		}

		protected override void OnDetaching() {
			base.OnDetaching(); if (this.AssociatedObject != null) {
				this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
			}
		}

		private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) {
			this.SelectedItem = e.NewValue;
		}
	}
}
